﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Data;
using System.Text;
using System.Collections;
namespace FTchina.SMSServer
{
    /// <summary>
    ///SMSSender 的摘要说明
    /// </summary>
    public class SMSSender
    {

        public SMSSender()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }

        /// <summary>
        /// 服务器地址
        /// </summary>
        public static String ServerURL
        {
            get
            {
                string sql = "SELECT   ServerUrl FROM   ServerInfo order by id desc limit 1";
                using (DataTable dt = shujuku.GetDataTable(sql))
                {
                    return dt.Rows[0][0].ToString();
                }
            }
        }
        /// <summary>
        /// 用户唯一编码
        /// </summary>
        private static String SenderID
        {
            get
            {
                string sql = "SELECT SenderID FROM   ServerInfo order by id desc limit 1 ";
                using (DataTable dt = shujuku.GetDataTable(sql))
                {
                    return dt.Rows[0][0].ToString();
                }
            }
        }

        /// <summary>
        /// 接收短信的地址
        /// </summary>
        private static String ReceivePath
        {
            get { return "/smstask/receive.aspx"; }
        }

        /// <summary>
        /// 酒店名称
        /// </summary>
        private static String HotelName
        {
            get
            {
                string sql = "SELECT  HotelName FROM   HotelInfo order by id desc  limit 1 ";
                using (DataTable dt = shujuku.GetDataTable(sql))
                {
                    return dt.Rows[0][0].ToString();
                }
            }
        }
        /// <summary>
        /// 酒店地址
        /// </summary>
        private static String HotelAddress
        {
            get
            {
                string sql = "SELECT  HotelAddress FROM   HotelInfo order by id desc  limit 1 ";
                using (DataTable dt = shujuku.GetDataTable(sql))
                {
                    return dt.Rows[0][0].ToString();
                }
            }
        }
        /// <summary>
        /// 酒店电话
        /// </summary>
        private static String HotelTel
        {
            get
            {
                string sql = "SELECT   HotelTel FROM   HotelInfo order by id desc  limit 1 ";
                using (DataTable dt = shujuku.GetDataTable(sql))
                {
                    return dt.Rows[0][0].ToString();
                }
            }
        }


        #region 向服务器推送短信


        /// <summary>
        /// 根据客户分组ID发送短信
        /// </summary>
        /// <param name="CustomerID"></param>
        /// <param name="Sms_ExampleID"></param>
        /// <returns></returns>
        public static void SendSmsByGroupID(string GroupID, string Scontent)
        {
            using (DataTable dt = shujuku.GetDataTable("select id from CustomerList where CustomerGroupID='" + GroupID + "'"))
            {
                foreach (DataRow dr in dt.Rows)
                {

                    SendSmsByCustomerID(dr["id"].ToString(), Scontent);
                }
            }
        }

        /// <summary>
        /// 根据客户ID集合 发送短信
        /// </summary>
        /// <param name="CustomerID"></param>
        /// <param name="Sms_ExampleID"></param>
        /// <returns></returns>
        public static void SendSmsByCustomerIDs(string CustomerIDs, string Scontent)
        {

            foreach (string id in CustomerIDs.Split(','))
            {
                if (id.Length > 0)
                {
                    SendSmsByCustomerID(id, Scontent);
                }
            }
        }


        /// <summary>
        /// 根据客户ID发送短信
        /// </summary>
        /// <param name="CustomerID"></param>
        /// <param name="Sms_ExampleID"></param>
        /// <returns></returns>
        public static String SendSmsByCustomerID(string CustomerID, string Scontent)
        {
            FTchina.Models.CustomerList mCustomerList = FTchina.BLL.CustomerListManager.GetCustomerListByid(Convert.ToInt32(CustomerID));
            string SmsExample = Scontent;
            string chenghu = (mCustomerList.CustormeSex == "男") ? "先生" : "女士";
            string xing = (mCustomerList.CustomerName.Length > 1) ? mCustomerList.CustomerName.Substring(0, 1) : mCustomerList.CustomerName;
            return Send2SeverWithLog(mCustomerList.CustomerTel0, MakeSmsReplacExample(SmsExample, xing, chenghu, "", ""));//发送短信
        }


        /// <summary>
        /// 根据客户ID、短信模板ID发送短信
        /// </summary>
        /// <param name="CustomerID"></param>
        /// <param name="Sms_ExampleID"></param>
        /// <returns></returns>
        public static String SendSmsByCustomerIDAndSms_ExampleID(string CustomerID, string Sms_ExampleID)
        {
            FTchina.Models.CustomerList mCustomerList = FTchina.BLL.CustomerListManager.GetCustomerListByid(Convert.ToInt32(CustomerID));
            string SmsExample = GetSmstemp(Sms_ExampleID);
            string chenghu = (mCustomerList.CustormeSex == "男") ? "先生" : "女士";
            string xing = (mCustomerList.CustomerName.Length > 1) ? mCustomerList.CustomerName.Substring(0, 1) : mCustomerList.CustomerName;
            return Send2SeverWithLog(mCustomerList.CustomerTel0, MakeSmsReplacExample(SmsExample, xing, chenghu, "", ""));//发送短信
        }




        /// <summary>
        /// 将短信发送至服务器
        /// </summary>
        /// <param name="target">目标手机号15605460546,18605460546英文逗号隔开</param>
        /// <param name="content">发送内容</param>
        /// <returns></returns>
        public static String Send2SeverWithLog(string target, string content)
        {

            string result = string.Empty;
            try
            {
                string parm = "senderid={0}&target={1}&content={2}";
                string full = string.Format(parm, SenderID, target, content);

                bool flag = true;
                foreach (string str in target.Split(','))
                {
                    if (!basic.ValidateMobile(str))
                    {
                        flag = false;
                        result = "手机号码错误，发送取消";
                        break;
                    }
                }
                if (flag)
                {
                    result = basic.Post2Http("http://" + ServerURL + ReceivePath, Encoding.UTF8, full);
                }
                //插入发送日志
                InsertSmsLog(target, content, basic.GetSqliteDate(), result);

                return result;
            }
            catch (Exception e)
            {
                LogNet.LogBLL.error(e.Message);
                return "参数设置错误";
            }

        }
        /// <summary>
        /// 插入发送日志
        /// </summary>
        /// <param name="Target"></param>
        /// <param name="Scontent"></param>
        /// <param name="SendTime"></param>
        /// <param name="Result"></param>
        private static void InsertSmsLog(string Target, string Scontent, string SendTime, string Result)
        {
            string sms_log_sql = @"INSERT INTO [Send_log]
           ([SendTarget]
           ,[SendContent]
           ,[SendTime],[result],[count])
     VALUES
           ('{0}'
           ,'{1}'
           ,'{2}','{3}','{4}')";


            ArrayList al = new ArrayList();//存放短信
            string[] TargetS = Target.Split(',');

            List<String> ms = new FTchina.SMSServer.SMSSplite().StringSplit(Scontent);
            foreach (string tg in TargetS)
            {
                if (tg.Trim().Length == 0) continue;
                //string sqlx = string.Empty;
                //foreach (String m in ms)
                //{

                //}
                al.Add(string.Format(sms_log_sql, tg.Trim(), Scontent, SendTime, Result, ms.Count));
            }

            FTchina.shujuku.ExecuteSqlTransaction(al);
        }
        #endregion


        #region 生成短信内容





        /// <summary>
        /// 根据默认模板生成短信内容
        /// </summary>
        /// <param name="CustomerName"></param>
        /// <param name="CustomerSex"></param>
        /// <param name="Dinner"></param>
        /// <param name="Room"></param>
        /// <returns></returns>
        public static string GetSmsResult(string CustomerName, string CustomerSex, string zao, string zhong, string wan, string Room, string zaoDate, string ZhongDate, string WanDate, string selfdate)
        {
            //尊敬的{姓名称呼}，您预定是的{时间}，{房间名称}，我们将恭候您的光临！{地址}{联系电话}。
            string tmp = string.Empty;
            string smstemp = GetSmstemp();
            string chenghu = (CustomerSex == "男") ? "先生" : "女士";
            string xing = (CustomerName.Length > 1) ? CustomerName.Substring(0, 1) : CustomerName;
            string shijian = string.Empty;//到店时间

            string FinalDate = (selfdate.Trim().Length > 0) ? selfdate : DateTime.Now.ToString("M月d日");

            #region 处理预定的房间、餐厅的格式

            string yuding = string.Empty;
            if (wan.Length > 0)
            {


                // yuding += "晚餐:" + wan + ";";
                yuding += wan + "，";
            }
            if (zhong.Length > 0)
            {


                //  yuding += "午餐:" + zhong + ";";
                yuding += zhong + "，";
            }
            if (zao.Length > 0)
            {


                //  yuding += "早餐:" + zao + ";";
                yuding += zao + "，";
            }


            if (Room.Length > 0)
            {
                if (yuding.Length > 0)
                {
                    yuding += "房间:" + Room + ";";

                }
                else
                {
                    yuding = "房间:" + Room + ";";
                }
            }
            yuding = yuding.Replace(',', '，');
            #endregion
            if (zaoDate.Length > 0)
            {
                if (selfdate.Trim().Length > 0)
                {
                    shijian = FinalDate + zaoDate;//前天定第二天早餐
                }
                else
                {
                    shijian = DateTime.Now.AddDays(1).ToString("M月d日") + zaoDate;//前天定第二天早餐

                }

            }
            if (WanDate.Length > 0)
            {
                
                shijian = FinalDate + WanDate;

            }
            if (ZhongDate.Length > 0)
            {
               
                shijian = FinalDate + ZhongDate;

            }
           
            smstemp = MakeSmsReplacExample(smstemp, xing, chenghu, shijian, yuding);
            return smstemp;
        }


        /// <summary>
        /// 对短信模板进行替换
        /// </summary>
        /// <param name="smstemp">短信模板</param>
        ///<param name="xing">姓氏</param>
        /// <param name="chenghu">称呼</param>
        /// <param name="shijian">时间</param>
        /// <param name="yuding">预定内容</param>
        /// <returns></returns>
        private static string MakeSmsReplacExample(string smstemp, string xing, string chenghu, string shijian, string yuding)
        {
            smstemp = smstemp.Replace("{姓名称呼}", xing + chenghu);
            if (shijian.Length == 0) smstemp = smstemp.Replace("{到店时间}", shijian);
            smstemp = smstemp.Replace("{到店时间}", shijian);
            smstemp = smstemp.Replace("{房间名称}", yuding).Replace(";，", "，").Replace(";,", "，").Replace("，，", "，");
            smstemp = smstemp.Replace("{地址}", FTchina.SMSServer.SMSSender.HotelAddress);
            smstemp = smstemp.Replace("{联系电话}", FTchina.SMSServer.SMSSender.HotelTel);
            smstemp = smstemp.Replace("{酒店名称}", FTchina.SMSServer.SMSSender.HotelName);
            return smstemp;
        }



        /// <summary>
        /// 获取默认短信模板
        /// </summary>
        /// <returns></returns>
        protected static String GetSmstemp()
        {
            string execsql = string.Empty;
            string testsql = "select   *  from SMS_Example where isdefault=1 order by id desc  limit 1 ";
            if (shujuku.testread(testsql))
            {
                execsql = testsql;
            }
            else
            {
                execsql = "select   * from SMS_Example order by id desc  limit 1 ";

            }
            return shujuku.GetDataTable(execsql).Rows[0]["smscontent"].ToString();
        }
        /// <summary>
        /// 获取指定短信模板
        /// </summary>
        /// <returns></returns>
        protected static String GetSmstemp(string SMS_ExampleID)
        {
            string execsql = string.Empty;
            string testsql = "select *  from SMS_Example where id='{0}' order by id desc  limit 1  ";
            execsql = string.Format(testsql, SMS_ExampleID);
            return shujuku.GetDataTable(execsql).Rows[0]["smscontent"].ToString();
        }



        /// <summary>
        /// 根据客户ID、模板获取待发送短信，作为样例进行查看
        /// </summary>
        /// <param name="CustomerID"></param>
        /// <param name="Sms_ExampleID"></param>
        /// <returns></returns>
        public static String GetSmsByCustomerID(string CustomerID, string Scontent)
        {
            FTchina.Models.CustomerList mCustomerList = FTchina.BLL.CustomerListManager.GetCustomerListByid(Convert.ToInt32(CustomerID));
            string SmsExample = Scontent;
            string chenghu = (mCustomerList.CustormeSex == "男") ? "先生" : "女士";
            string xing = (mCustomerList.CustomerName.Length > 1) ? mCustomerList.CustomerName.Substring(0, 1) : mCustomerList.CustomerName;
            return MakeSmsReplacExample(SmsExample, xing, chenghu, "", "");//短信示例
        }

        /// <summary>
        /// 只获取替换了关键字的短信内容
        /// </summary>
        /// <param name="CustomerID"></param>
        /// <param name="Sms_ExampleID"></param>
        /// <returns></returns>
        public static String GetFormatedOnlySms(string Scontent)
        {
            return MakeSmsReplacExample(Scontent, "", "", "", "");//短信示例
        }



        #endregion




    }
}